using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class app_frame_help : System.Web.UI.Page
{
    string strPageSetId = "ps_job_schedules";
    DataSet dseInputInfo = new DataSet();
    DataSet dsePageInfo = new DataSet();
    HtmlForm frmObj;
    string strErrMessage = "";
    string refererURL = "";
    string dtFormat = "MM-dd-yyyy HH:mm:ss";
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Request.UrlReferrer.ToString().IndexOf("DisplayGrid") > 0)
        //    refererURL = Request.UrlReferrer.ToString();
        
        security hdds = new security();
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        //Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
        {
            if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                tblcontrols.Visible = false;
                return;
            }
        }

        setRequestURL();
        //loadDynamicControls();
        if (this.Master.FindControl("Form1") != null)
        {
            frmObj = (HtmlForm)this.Master.FindControl("Form1");
        }
        PageInfoLoad PIL = new PageInfoLoad();
        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPageSetId);
        if (!Page.IsPostBack)
        {
            //loadOwneridDropDown();
            p_job_schedules_owner_id.Value = Session["user_afrowid"].ToString();
            txt_p_job_schedules_owner_id.Text = Session["userid"].ToString();
        }

        CheckForChangeOwner();
        CheckEditOperation();
        //p_help_help_desc.Visible=false;
        if (IsPostBack) { getpageicons(); return; } // Modified by srivatsan
        //p_job_schedules_jb_sch_time.Attributes.Add("onchange", "javascript:alert('ss');");
        //p_job_schedules_jb_sch_time.Attributes.Add("onselect", "javascript:alert('ss');");
        p_job_schedules_jb_sch_recurr_type.Attributes.Add("onchange", "javascript:putValues();");
        p_job_schedules_jb_sch_id.Text = getSeqNumber();
        loadCategory();
        loadRecurrTypes();
        if (btnUpdate.Visible)
        {
            loadMasterValues();
        }
        //if (Request.QueryString["CPY"] != null)//to get the new ID
        //    if (Request.QueryString["CPY"].ToString() == "0")
        //        p_job_schedules_jb_sch_id.Text = getSeqNumber();
        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                loadMasterValues();
                //loadChildValues();
                //showParamterContent(true, Request.QueryString["PK"].ToString());
                p_job_schedules_jb_sch_id.Text = getSeqNumber();
                //p_job_schedules_owner_id.SelectedValue = Session["user_afrowid"].ToString();
                p_job_schedules_owner_id.Value = Session["user_afrowid"].ToString();
                txt_p_job_schedules_owner_id.Text = Session["userid"].ToString();
            }
        }
        if (!Page.IsPostBack)
        {
            getpageicons(); // Added by srivatsan
        }
        isViewMode();
    }
    private void isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                DynamicDisplayI ddi = new DynamicDisplayI();
                ddi.disableControls(this);
                ddi = null;
                lblHeader.Text = "Job Scheduler - View";// added by Prithi on Aug-04-2008
                img_cal_1.Visible = false;
                img_cal_2.Visible = false;
                img_cal_3.Visible = false;
            }
    }    
    private void setRequestURL()//implemented by sanal on 13 Dec 2007
    {
        if (!IsPostBack)
            //hfRequestURL.Value = Request.UrlReferrer.ToString();
            hfRequestURL.Value = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();
    }
    private string getSeqNumber()
    {
        try
        {
            int ret = 0;
            HDDatabase hd = new HDDatabase();
            DataSet ds = hd.GetDataset("SELECT max(cast(jb_sch_id as int)+1) AS Count FROM sy_jb_sch");
            if (ds == null)
            {
                ret = 1000;
            }
            else
            {
                try
                {
                    ret = Convert.ToInt32(ds.Tables[0].Rows[0]["Count"].ToString());
                }
                catch (Exception e)
                { }
                if (ret < 1000)
                    ret = ret + 1000;
            }
            hd = null;
            return ret.ToString();
        }
        catch (Exception e)
        {
            return "1000";
        }
    }
    private void loadMasterValues()
    {
        try
        {
            string sPageKey = "";
            if (Request.QueryString["PK"] != null)
                sPageKey = Request.QueryString["PK"].ToString();
            if (sPageKey == "") return;
            HDDatabase hd = new HDDatabase();
            DataSet ds = new DataSet();
            ds = hd.GetDataset("select * from sy_jb_sch where af_row_id='" + sPageKey + "'");
            
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    p_job_schedules_af_row_id.Value = sPageKey;
                    p_job_schedules_jb_sch_id.Text = ds.Tables[0].Rows[0]["jb_sch_id"].ToString();
                    p_job_schedules_jb_sch_eff_from.Text =getDateTimeValue( ds.Tables[0].Rows[0]["jb_sch_eff_from"].ToString());
                    p_job_schedules_jb_sch_recurr_value.Text = ds.Tables[0].Rows[0]["jb_sch_recurr_value"].ToString();
                    p_job_schedules_jb_sch_recurr_type.SelectedValue = ds.Tables[0].Rows[0]["jb_sch_recurr_type"].ToString();
                    p_job_schedules_jb_sch_time.Text = getDateTimeValue(ds.Tables[0].Rows[0]["jb_sch_time"].ToString());
                    p_job_schedules_jb_id.SelectedValue = ds.Tables[0].Rows[0]["jb_id"].ToString();
                    p_job_schedules_jb_sch_eff_to.Text = getDateTimeValue(ds.Tables[0].Rows[0]["jb_sch_eff_to"].ToString());
//                    p_job_schedules_owner_id.SelectedValue = ds.Tables[0].Rows[0]["owner_id"].ToString();
                    p_job_schedules_owner_id.Value = ds.Tables[0].Rows[0]["owner_id"].ToString();
                    LoadEditPage LEP = new LoadEditPage();
                    txt_p_job_schedules_owner_id.Text = LEP.GetUserIDFromAfrowid(p_job_schedules_owner_id.Value);
                    LEP = null;
                }
            }

            ds = null;
            hd = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in messages.aspx:loadMasterValues: " + e.Message);
        }
    }
    private string getDateTimeValue(string inp)
    {
        try
        {
            DynamicDisplayI DDI = new DynamicDisplayI();
            string sTemp = DDI.getUsersDateTime(inp);
            if (sTemp == "") sTemp = inp;
            DateTime dt = DateTime.Parse(sTemp);
            return dt.ToString("MM-dd-yyyy HH:mm:ss");
        }
        catch (Exception e)
        {
            return inp;
        }
    }
    private void loadDynamicControls()
    {
        //if (IsPostBack) return;
        HiddenField hf = new HiddenField();
        hf.ID = "hf_ref_url";
        hf.EnableViewState = true;
        if (refererURL.Length > 0) hf.Value = refererURL;
        lbl_message.Controls.Add(hf);
    }

    private void loadRecurrTypes()
    {
        HDDatabase hd = new HDDatabase();
        p_job_schedules_jb_sch_recurr_type.Items.Clear();
        //DataSet ds = hd.GetDataset("select * from sy_acr_mem where acr_id=21 order by mem_seq");
        DataSet ds = hd.GetDataset("select * from sy_acr_mem where acr_id='60b914ef6b1eb217' order by mem_seq");        
        //p_job_scheules_jb_sch_recurr_type.Items.Add(new ListItem("", ""));
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                    p_job_schedules_jb_sch_recurr_type.Items.Add(new ListItem(dr["mem_name"].ToString(), dr["mem_id"].ToString()));
            }
        }
    }
    private void loadCategory()
    {
        HDDatabase hd = new HDDatabase();
        p_job_schedules_jb_id.Items.Clear();
        DataSet ds = hd.GetDataset("select DISTINCT jb_id from sy_job");
        //p_job_schedules_jb_id.Items.Add(new ListItem("", ""));
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                    p_job_schedules_jb_id.Items.Add(new ListItem(dr["jb_id"].ToString(), dr["jb_id"].ToString()));
            }
        }
    }
    private bool CheckEditOperation()
    {
        bool blnStatus = true;
        string strPageKey = "";
        bool IsEdit = false;
        if (Page.IsPostBack == false)
        {
            if (Request.QueryString["PK"] != null)
            {
                strPageKey = Request.QueryString["PK"].ToString();
                IsEdit = true;
            }
            if (IsEdit)
            {
                Master MA = new Master();
                blnStatus = MA.EditOperation(dsePageInfo, frmObj, strPageKey);
                lblHeader.Text = "Job Scheduler - Edit";// added by Prithi on Aug-04-2008
                if (blnStatus == false)
                {
                    strErrMessage = MA.ErrorMessage;
                    Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
                }
            }
        }
        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                btnSave.Visible = true;
                btnUpdate.Visible = false;
            }
            lblHeader.Text = "Job Scheduler - Copy";// added by Prithi on Aug-04-2008

        }
        else if (Request.QueryString["PK"] == null)
        {
            lblHeader .Text ="Job Scheduler - Add"; // added by Prithi on Aug-04-2008
            btnSave.Visible = true;
            btnUpdate.Visible = false;
        }
        else
        {
            btnUpdate.Visible = true;
            btnSave.Visible = false;
        }
        return blnStatus;
    }



    private bool SaveData()
    {
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPageSetId, frmObj, dsePageInfo,true);
        if (SR.errormessage != "")
        {
            strErrMessage = SR.errormessage;
            return false;
        }
        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }

    private bool UpdateData()
    {
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPageSetId, frmObj, dsePageInfo,false);
        if (SR.errormessage != "")
        {
            strErrMessage = SR.errormessage;
            return false;
        }
        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "UPDATE");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }
    private bool isInteger(string inp)
    {
        if (inp.Trim().Length == 0) return false;
        try
        {
            int i = Convert.ToInt32(inp);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    private bool isDateTime(string inp)
    {
        if (inp.Trim().Length == 0) return false;
        try
        {
            //30-11-2007 13:53:13
            //DateTime dt = DateTime.Parse(inp);
            DateTime dt = DateTime.ParseExact(inp,dtFormat, null);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    private bool validate()
    {
        try
        {
            //string ret = p_job_schedules_jb_sch_id.Text;
            if (p_job_schedules_jb_id.SelectedValue == "")
            {
                lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;Invalid Job ID.";//changed by prithi on 07-Aug-2008
                return false;
            }
            if (p_job_schedules_jb_sch_recurr_type.SelectedValue!="once")
            {
                if (!isInteger(p_job_schedules_jb_sch_recurr_value.Text))
                {
                    lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;Invalid Recurring Value Specified.";//changed by prithi on 07-Aug-2008
                    return false;
                }
                if (!isDateTime(p_job_schedules_jb_sch_eff_from.Text))
                {
                    lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;Invalid Schedule Time Specified.";//changed by prithi on 07-Aug-2008
                    return false;
                }
                if (!isDateTime(p_job_schedules_jb_sch_eff_to.Text))
                {
                    lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;Invalid Schedule Time Specified.";//changed by prithi on 07-Aug-2008
                    return false;
                }
            }
            if (!isDateTime(p_job_schedules_jb_sch_time.Text))
            {
                lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;Invalid Schedule Time Specified.";//changed by prithi on 07-Aug-2008
                return false;
            }
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    protected void btnSave_ServerClick(object sender, EventArgs e)
    {        
        //return;         
        //string ret = p_help_help_desc.Text;   
        if (!validate()) return;
        if (SaveData())
        {
            //Response.Write("Data Inserted Successfully");
            string refURL = getRefURL();
            if (refURL.Length > 0)
                Response.Redirect(refURL);
            else
                lbl_message.Text = "Data Inserted Successfully";//changed by prithi on 07-Aug-2008
        }
        else
        {
            lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. Error:" + ErrorMessage;
        }
    }
    protected void btnUpdate_ServerClick(object sender, EventArgs e)
    {
        if (!validate()) return;
        if (UpdateData())
        {
            string refURL = getRefURL();
            if (refURL.Length > 0)
                Response.Redirect(refURL);
            else
                lbl_message.Text = "&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Data Updated Successfully.";
        }
        else
        {
            lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. Error:" + ErrorMessage;
        }
    }

    protected void btnreset_ServerClick(object sender, EventArgs e)
    {
        //Response.Redirect(Request.RawUrl);
        try
        {
            if (p_job_schedules_jb_id.Items.Count>0)   p_job_schedules_jb_id.SelectedIndex = 0;
            p_job_schedules_jb_sch_eff_from.Text = "";
            p_job_schedules_jb_sch_eff_to.Text = "";
            p_job_schedules_jb_sch_recurr_value.Text = "";
            p_job_schedules_jb_sch_time.Text = "";
            p_job_schedules_jb_sch_recurr_type.SelectedIndex = 0;
        }
        catch (Exception ee)
        {

        }
    }
    private string getRefURL()
    {
        string ret = "";
        try
        {
            return hfRequestURL.Value;
            //DynamicDisplayI di = new DynamicDisplayI();
            //HiddenField hf = (HiddenField)di.FindControl(this.Controls, "hf_ref_url");
            //ret = hf.Value;
            //di = null;
            //return ret;
        }
        catch (Exception e)
        {
            return "";
        }

    }
    
    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }
    private void getpageicons() // Added by srivatsan to get page icon
    {
        PageIcons icons = new PageIcons();
        HDDatabase Hdd = new HDDatabase();
        try
        {
            string pagesetid = Request.QueryString["pgs_id"].ToString();

            lblHeader.Text = "&nbsp;" + icons.geticontextfrompageset(pagesetid, 2) + "&nbsp;" + lblHeader.Text;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
            lblHeader.Text = "<img src=" + PageIcons.strdefaulticon.ToString() + "></img>&nbsp;" + lblHeader.Text;
        }
        finally
        {
            icons = null;
            Hdd = null;
        }

    }

    private void CheckForChangeOwner()  // Added by srivatsan to Check if user can change owner
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects(HttpContext.Current.Request.QueryString["pgs_id"].ToString(), "change_owner");
            if (status == false)
            {

                txt_p_job_schedules_owner_id.Enabled = false;

            }
            else
            {
                PageCommonFunctions PCF = new PageCommonFunctions();
                PCF.AddSearchLink(ref tdownerid, "owner_id", "p_job_schedules_owner_id", "txt_p_job_schedules_owner_id", "f496930dfe0b690f");
                PCF = null;
            }

            sec = null;
        }
        catch
        {

        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
}
